package com.example.demo.config;

import com.example.demo.common.IgnoreAccessTokenCheck;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 解决跨域问题
 *
 * */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    /**
     * 跨域处理
     * */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedOriginPatterns("*");
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //根据接口头部的注解做拦截
        registry.addInterceptor(new HandlerInterceptor() {
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    Method method = handlerMethod.getMethod();

                    IgnoreAccessTokenCheck ignoreAccessTokenCheck = method.getAnnotation(IgnoreAccessTokenCheck.class); //省略token注解

                    /*拦截请求头上带有 ApiOperation 注解的
                      然后获取对应的token信息 判断token是否有效
                    if (method.isAnnotationPresent(ApiOperation.class) ){
                        String userName = null;
                        String userId = null;
                        String organizationId = null;
                        String token = request.getHeader(TokenUtils.AccessToken_HEADER_NAME);
                        String deviceInfo = request.getHeader(TokenUtils.DeviceInfo_HEADER_NAME);
                        String terminalInfo = request.getHeader(TokenUtils.Terminal_HEADER_NAME);

                        if (token!= null &&  !token.trim().equals("")) {
                            userName = TokenUtils.getUserInfoFromToken(token);
                        }
                        if(ignoreAccessTokenCheck == null && userName == null) {
                            throw new RuntimeException("没有访问权限");
                        }
                        user.setUserName(userName);
                        user.setUserId(userId);
                        user.setOrganizationId(organizationId);
                    }*/

                }
                return true;
            }

        });

        //注册拦截器，对超级管理员系统进行权限验证
        InterceptorRegistration registration2 = registry.addInterceptor(new HandlerInterceptor() {
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {

                //HttpServletRequest 获取请求信息 自定义一些规则  符合逻辑返回true
                System.out.println(request.getRequestURI());
                return true;
            }
        });
        /*指定拦截器要拦截的请求(支持*通配符)*/
        registration2.addPathPatterns("/api/**");
        //指定拦截器不拦截的请求(支持*通配符)
        registration2.excludePathPatterns("/super/toLogin");

    }



}
